<template>
  <!-- 图表-饼状图-组件-->
  <div ref="chart"></div>
</template>
<script>
// import 'echarts/theme/shine'
export default {
  name: 'cEcharts',
  props: {
    data: [Object, Array], // 数据源
    title: Object, // 标题
    name: String, // 组件name
    tooltipStr: { // 提示
      type: String,
      default: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: { // 图例组件
      type: Object,
      default: () => {
        return { orient: 'vertical', right: 10, formatter: '{name}' }
      }
    },
    series: Object, // 配置-单项
    labelShow: Boolean, // 提示
    type: String, // 类型
    option: Object // 配置-所有
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    seriesNew() {
      if (!this.series) {
        const def = {
          name: this.name || '', type: 'pie',
          radius: '50%', data: this.data
        }
        if (!this.labelShow) { // 取消指示
          def.label = { show: false }
          def.labelLine = { show: false }
        }
        return def
      }
      return this.series
    }
  },
  created() {
  },
  mounted() {
    this.initChart() // 初始化-图表
  },
  methods: {
    // 初始化-图表
    initChart() {
      this.chart = this.$echarts.init(this.$refs.chart, 'shine')
      this.setOption()
    },
    // 配置--图表
    setOption() {
      if (this.option && Object.keys(this.option).length) { // 有配置
        this.chart.setOption(this.option)
      } else { // 无配置
        if (this.type) { // 存在
          let option = {}
          switch (this.type) {
            case 'pie': { // 饼状
              option = {
                legend: this.legend,
                title: this.title,
                tooltip: { trigger: 'item', formatter: this.tooltipStr },
                series: [this.seriesNew]
              }
              break
            }
          }
          this.chart.setOption(option)
        }
      }
    }
  },
  filters: {

  },
  watch: {
    option(newVal) {
      // this.chart = this.$echarts.init(this.$refs.chart, 'shine')
      this.chart.setOption(newVal)
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
